package order

import (
	"context"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/common/moneyx"
	"mall/common/utils/pointy"
	"mall/service/order/model"
	"mall/service/order/rpc/internal/svc"
	"mall/service/order/rpc/internal/utils/errorhandler"
	"mall/service/order/rpc/types/order"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendGetOrderListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendGetOrderListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendGetOrderListLogic {
	return &BackendGetOrderListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendGetOrderListLogic) BackendGetOrderList(in *order.BackendOrderListReq) (*order.BackendOrderListResp, error) {
	// logx.Infof("BackendGetOrderList : %+v ", in)

	var orderBys []string
	if len(in.OrderBy) > 0 {
		for _, orderBy := range in.OrderBy {
			order := " ASC"
			if orderBy.Order == "1" {
				order = " DESC"
			}
			switch orderBy.Field {
			case "id":
				orderBys = append(orderBys, model.OrderColumns.ID+order)
			case "createdAt":
				orderBys = append(orderBys, model.OrderColumns.CreatedAt+order)
			}
		}
	}

	var stati string
	var orderType string
	if len(in.FilterBy) > 0 {
		for _, filterBy := range in.FilterBy {
			switch filterBy.Field {
			case "status":
				stati = filterBy.In
			case "type":
				orderType = filterBy.In
			}
		}
	}

	var page uint64
	var pageSize uint64
	var restricted bool
	var withCount int
	var preCount int64
	filterMap := make(map[string]map[string][]any)
	resp := &order.BackendOrderListResp{}
	if in.Ids != nil && len(*in.Ids) > 0 {
		if vals := modelx.UniqueInterfaces(*in.Ids, 64); len(vals) == 0 {
			return resp, nil
		} else {
			filterMap[model.OrderColumns.ID] = map[string][]any{
				"in": vals,
			}
			restricted = true
			withCount = -1
			preCount = int64(len(vals))
		}
	}

	var statusIsSet bool
	var isAll bool
	statusMap := make(map[string][]any)
	switch orderType {
	case "1": // 全部
		statusMap["notIn"] = []any{
			globalkey.OrderTradeStateUserDeleted,
			globalkey.OrderTradeStateAdminDeleted,
		}
		isAll = true
	case "2": // 待发货
		filterMap[model.OrderColumns.TradeState] = map[string][]any{
			"equalTo": {globalkey.OrderTradeStatePaid},
		}
		statusIsSet = true
	case "3": // 发货中
		filterMap[model.OrderColumns.TradeState] = map[string][]any{
			"equalTo": {globalkey.OrderTradeStateShipping},
		}
		statusIsSet = true
	case "4": // 已发货
		filterMap[model.OrderColumns.TradeState] = map[string][]any{
			"in": {
				globalkey.OrderTradeStateShipped,
				globalkey.OrderTradeStateDelivering,
				globalkey.OrderTradeStateDelivered,
			},
		}
		statusIsSet = true
	case "5": // 已收货
		filterMap[model.OrderColumns.TradeState] = map[string][]any{
			"in": {
				globalkey.OrderTradeStateConfirmed,
				globalkey.OrderTradeStateAutoConfirmed,
			},
		}
		statusIsSet = true
	case "6": // 已评价
		filterMap[model.OrderColumns.TradeState] = map[string][]any{
			"in": {
				globalkey.OrderTradeStateReviewed,
				globalkey.OrderTradeStateAutoReviewed,
			},
		}
		statusIsSet = true
	case "7": // 已完成（无售后选项）
		filterMap[model.OrderColumns.TradeState] = map[string][]any{
			"equalTo": {globalkey.OrderTradeStateFulfilled},
		}
		statusIsSet = true
	case "8": // 已关闭
		filterMap[model.OrderColumns.TradeState] = map[string][]any{
			"equalTo": {globalkey.OrderTradeStateClosed},
		}
		statusIsSet = true
	case "9": // 退款中
		filterMap[model.OrderColumns.TradeState] = map[string][]any{
			"in": {
				globalkey.OrderTradeStateRefundApply,
				globalkey.OrderTradeStateRefunding,
				globalkey.OrderTradeStateAdminRefunding,
			},
		}
		statusIsSet = true
	case "10": // 已退款
		filterMap[model.OrderColumns.TradeState] = map[string][]any{
			"in": {
				globalkey.OrderTradeStateRefunded,
				globalkey.OrderTradeStateAdminRefunded,
			},
		}
		statusIsSet = true
	case "11": // 售后
		filterMap[model.OrderColumns.TradeState] = map[string][]any{
			"in": {
				globalkey.OrderTradeStateReturnApply,
				globalkey.OrderTradeStateReturning,
			},
		}
		statusIsSet = true
	case "12": // 已完成售后
		filterMap[model.OrderColumns.TradeState] = map[string][]any{
			"equalTo": {globalkey.OrderTradeStateReturned},
		}
		statusIsSet = true
	case "13": // 其他
		filterMap[model.OrderColumns.TradeState] = map[string][]any{
			"in": {
				globalkey.OrderTradeStateNotPay,
				globalkey.OrderTradeStateUserCancelled,
				globalkey.OrderTradeStateAutoCancelled,
				globalkey.OrderTradeStateAdminCancelled,
			},
		}
		statusIsSet = true
	case "14": // 充值订单
		filterMap[model.OrderColumns.OrderType] = map[string][]any{
			"equalTo": {globalkey.OrderTypeVirtual},
		}
	}
	if orderType != "14" {
		filterMap[model.OrderColumns.OrderType] = map[string][]any{
			"moreThan": {globalkey.OrderTypeVirtual},
		}
	}

	if !restricted {
		page = in.Page
		pageSize = in.PageSize
		withCount = 1
	}

	if in.Sn != nil && len(strings.TrimSpace(*in.Sn)) >= 5 {
		filterMap[model.OrderColumns.OrderSN] = map[string][]any{
			"contain": {strings.TrimSpace(*in.Sn)},
		}
	}

	var startTimeIn []any
	var endTimeIn []any
	if in.StartTime != nil && len(strings.TrimSpace(*in.StartTime)) > 0 {
		if startTime, err := modelx.ParseLocalDate(strings.TrimSpace(*in.StartTime)); err == nil {
			startTimeIn = append(startTimeIn, startTime)
		}
	}
	if in.EndTime != nil && len(strings.TrimSpace(*in.EndTime)) > 0 {
		if endTime, err := modelx.ParseLocalDate(strings.TrimSpace(*in.EndTime)); err == nil {
			endTimeIn = append(endTimeIn, endTime)
		}
	}
	createdAtMap := make(map[string][]any)
	if len(startTimeIn) > 0 {
		createdAtMap["moreThanOrEqualTo"] = startTimeIn
	}
	if len(endTimeIn) > 0 {
		createdAtMap["lessThan"] = endTimeIn
	}
	filterMap[model.OrderColumns.CreatedAt] = createdAtMap

	// logrus.Info(fmt.Sprintf("BackendGetOrderList filterMap: %+v", filterMap))

	if isAll {
		ret, _, err := l.svcCtx.Order.GetList(l.ctx, model.M{
			"statistic": "1",
		}, 5, filterMap)
		if err != nil {
			// return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			logx.Errorw("BackendGetOrderList GetList statistic err", logx.Field("detail", err.Error()))
		} else if len(ret) > 0 {
			statusStatisticMap := make(map[uint32]uint32)
			var total uint
			for _, v := range ret {
				switch uint32(v.TradeState) {
				case globalkey.OrderTradeStatePaid:
					statusStatisticMap[2] += uint32(v.Growth)
				case globalkey.OrderTradeStateShipping:
					statusStatisticMap[3] += uint32(v.Growth)
				case globalkey.OrderTradeStateShipped, globalkey.OrderTradeStateDelivering, globalkey.OrderTradeStateDelivered:
					statusStatisticMap[4] += uint32(v.Growth)
				case globalkey.OrderTradeStateConfirmed, globalkey.OrderTradeStateAutoConfirmed:
					statusStatisticMap[5] += uint32(v.Growth)
				case globalkey.OrderTradeStateReviewed, globalkey.OrderTradeStateAutoReviewed:
					statusStatisticMap[6] += uint32(v.Growth)
				case globalkey.OrderTradeStateFulfilled:
					statusStatisticMap[7] += uint32(v.Growth)
				case globalkey.OrderTradeStateClosed:
					statusStatisticMap[8] += uint32(v.Growth)
				case globalkey.OrderTradeStateRefundApply, globalkey.OrderTradeStateRefunding, globalkey.OrderTradeStateAdminRefunding:
					statusStatisticMap[9] += uint32(v.Growth)
				case globalkey.OrderTradeStateRefunded, globalkey.OrderTradeStateAdminRefunded:
					statusStatisticMap[10] += uint32(v.Growth)
				case globalkey.OrderTradeStateReturnApply, globalkey.OrderTradeStateReturning:
					statusStatisticMap[11] += uint32(v.Growth)
				case globalkey.OrderTradeStateReturned:
					statusStatisticMap[12] += uint32(v.Growth)
				default:
					statusStatisticMap[13] += uint32(v.Growth)
				}
				if v.TradeState != uint16(globalkey.OrderTradeStateUserDeleted) && v.TradeState != uint16(globalkey.OrderTradeStateAdminDeleted) {
					total += v.Growth
				}
			}
			statusStatisticMap[uint32(1)] = uint32(total)
			resp.StatusStatisticMap = statusStatisticMap
		}
	}

	if !statusIsSet {
		// logrus.Info(fmt.Sprintf("BackendGetOrderList in.Status: %+v", in.Status))
		statusIn := modelx.UniqueInterfaces(stati, 32)
		if len(statusIn) > 0 {
			statusMap["in"] = statusIn
		}
		if in.TradeState != nil {
			statusMap["equalTo"] = []any{*in.TradeState}
		}
		filterMap[model.OrderColumns.TradeState] = statusMap
	}

	if in.Sn != nil && len(*in.Sn) > 12 {
		filterMap[model.OrderColumns.OrderSN] = map[string][]any{
			"startWith": []any{*in.Sn},
		}
	}

	var orderBy string
	if len(orderBys) > 0 {
		orderBy = strings.Join(orderBys, ",")
	} else {
		orderBy = model.OrderColumns.ID + " DESC"
	}
	res, count, err := l.svcCtx.Order.GetList(l.ctx, model.M{
		"page":     page,
		"pageSize": pageSize,
		"orderBy":  orderBy,
	}, withCount, filterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if restricted {
		count = preCount
	}
	resp.Total = uint64(count)

	if len(res) > 0 {
		var oids []any
		for _, v := range res {
			oids = append(oids, v.ID)
		}

		idSkuMap := make(map[uint64][]*order.OrderSkuInfo)
		if in.WithSkus != nil && *in.WithSkus > 0 {
			subFilterMap := make(map[string]map[string][]any)
			subFilterMap[model.OrderItemColumns.OrderID] = map[string][]any{
				"in": oids,
			}
			list, _, err := l.svcCtx.Order.GetItemList(l.ctx, model.M{}, -1, subFilterMap)
			if err != nil {
				return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			}

			if len(list) > 0 {
				for _, v := range list {
					idSkuMap[v.OrderID] = append(idSkuMap[v.OrderID], &order.OrderSkuInfo{
						Id:             &v.OrderItemID,
						OrderId:        &v.OrderID,
						ProductCode:    &v.ProductCode,
						SkuId:          &v.SkuID,
						SkuCode:        &v.SkuCode,
						Sku:            &v.Sku,
						ImageId:        pointy.GetPointer(strconv.FormatUint(v.SkuImageID, 10)),
						ImageUrl:       &v.SkuImageURL,
						ProductId:      &v.ProductID,
						EntryId:        &v.EntryID,
						Title:          &v.Title,
						Slug:           &v.Slug,
						ProductType:    pointy.GetPointer(uint32(v.ProductType)),
						BrandId:        &v.BrandID,
						BrandTitle:     &v.BrandTitle,
						BrandSlug:      &v.BrandSlug,
						GemPrice:       pointy.GetPointer(moneyx.FormatGem(int64(v.GemPrice))),
						RetailPrice:    pointy.GetPointer(moneyx.FormatAmount(int64(v.RetailPrice))),
						Quantity:       pointy.GetPointer(uint32(v.Quantity)),
						Weight:         pointy.GetPointer(moneyx.FormatWeight(int64(v.Weight))),
						TradeState:     pointy.GetPointer(uint32(v.TradeState)),
						Status:         pointy.GetPointer(uint32(v.Status)),
						GemAmount:      pointy.GetPointer(moneyx.FormatGem(int64(v.GemAmount))),
						RetailAmount:   pointy.GetPointer(moneyx.FormatAmount(int64(v.RetailAmount))),
						Freight:        pointy.GetPointer(moneyx.FormatAmount(int64(v.Freight))),
						DiscountAmount: pointy.GetPointer(moneyx.FormatAmount(int64(v.DiscountAmount))),
						AdjustAmount:   pointy.GetPointer(moneyx.FormatAmount(int64(v.AdjustAmount))),
						ActualAmount:   pointy.GetPointer(moneyx.FormatAmount(int64(v.ActualAmount))),
						RefundAmount:   pointy.GetPointer(moneyx.FormatAmount(int64(v.RefundAmount))),
						RefundQuantity: pointy.GetPointer(uint32(v.RefundQuantity)),
						PostId:         &v.PostID,
						InviterId:      &v.InviterID,
					})
				}
			}
		}

		idAddressMap := make(map[uint64][]*order.OrderAddressInfo)
		if in.WithAddresses != nil && *in.WithAddresses > 0 {
			subFilterMap := make(map[string]map[string][]any)
			subFilterMap[model.OrderAddressColumns.OrderID] = map[string][]any{
				"in": oids,
			}
			list, _, err := l.svcCtx.Order.GetAddressList(l.ctx, model.M{}, -1, subFilterMap)
			if err != nil {
				return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			}

			if len(list) > 0 {
				for _, v := range list {
					idAddressMap[v.OrderID] = append(idAddressMap[v.OrderID], &order.OrderAddressInfo{
						Id:         &v.OrderAddressID,
						OrderId:    &v.OrderID,
						UserId:     &v.UserID,
						Consignee:  &v.Consignee,
						Mobile:     &v.Mobile,
						Province:   &v.Province,
						City:       &v.City,
						District:   &v.District,
						Street:     &v.Street,
						Address:    &v.DetailedAddress,
						PostalCode: &v.PostalCode,
						RegionCode: &v.RegionCode,
						Label:      &v.Label,
						Status:     pointy.GetPointer(uint32(v.Status)),
					})
				}
			}
		}

		idAdjustmentMap := make(map[uint64][]*order.OrderAdjustmentInfo)
		if in.WithAdjustments != nil && *in.WithAdjustments > 0 {
			subFilterMap := make(map[string]map[string][]any)
			subFilterMap[model.OrderAdjustmentColumns.OrderID] = map[string][]any{
				"in": oids,
			}
			list, _, err := l.svcCtx.Order.GetAdjustmentList(l.ctx, model.M{}, -1, subFilterMap)
			if err != nil {
				return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			}

			if len(list) > 0 {
				for _, v := range list {
					idAdjustmentMap[v.OrderID] = append(idAdjustmentMap[v.OrderID], &order.OrderAdjustmentInfo{
						Id:         &v.OrderAdjustmentID,
						OrderId:    &v.OrderID,
						Amount:     pointy.GetPointer(moneyx.FormatAmount(int64(v.Amount))),
						Memo:       &v.Memo,
						Status:     pointy.GetPointer(uint32(v.Status)),
						OperatedBy: &v.OperatedBy,
						OperatedAt: pointy.GetPointer(modelx.FormatNullDotTime(v.OperatedAt, "")),
					})
				}
			}
		}

		idDiscountMap := make(map[uint64][]*order.OrderDiscountInfo)
		if in.WithDiscounts != nil && *in.WithDiscounts > 0 {
			subFilterMap := make(map[string]map[string][]any)
			subFilterMap[model.OrderDiscountColumns.OrderID] = map[string][]any{
				"in": oids,
			}
			list, _, err := l.svcCtx.Order.GetDiscountList(l.ctx, model.M{}, -1, subFilterMap)
			if err != nil {
				return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			}

			if len(list) > 0 {
				for _, v := range list {
					idDiscountMap[v.OrderID] = append(idDiscountMap[v.OrderID], &order.OrderDiscountInfo{
						Id:               &v.OrderDiscountID,
						OrderId:          &v.OrderID,
						SkuId:            &v.SkuID,
						ProductId:        &v.ProductID,
						Title:            &v.Title,
						Slug:             &v.Slug,
						ActivityId:       &v.ActivityID,
						ActivityRuleId:   &v.ActivityRuleID,
						CouponTemplateId: &v.CouponTemplateID,
						CouponId:         &v.CouponID,
						GrouponAmount:    pointy.GetPointer(moneyx.FormatAmount(int64(v.GrouponAmount))),
						WholesaleAmount:  pointy.GetPointer(moneyx.FormatAmount(int64(v.WholesaleAmount))),
						CouponAmount:     pointy.GetPointer(moneyx.FormatAmount(int64(v.CouponAmount))),
						ActivityAmount:   pointy.GetPointer(moneyx.FormatAmount(int64(v.ActivityAmount))),
						IntegralAmount:   pointy.GetPointer(moneyx.FormatAmount(int64(v.IntegralAmount))),
						DiscountAmount:   pointy.GetPointer(moneyx.FormatAmount(int64(v.DiscountAmount))),
						Integrals:        &v.Integrals,
					})
				}
			}
		}

		idPaymentMap := make(map[uint64][]*order.OrderPaymentInfo)
		if in.WithPayments != nil && *in.WithPayments > 0 {
			subFilterMap := make(map[string]map[string][]any)
			subFilterMap[model.OrderPaymentColumns.OrderID] = map[string][]any{
				"in": oids,
			}
			list, _, err := l.svcCtx.Order.GetPaymentList(l.ctx, model.M{}, -1, subFilterMap)
			if err != nil {
				return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			}

			if len(list) > 0 {
				for _, v := range list {
					idPaymentMap[v.OrderID] = append(idPaymentMap[v.OrderID], &order.OrderPaymentInfo{
						Id:      &v.OrderPaymentID,
						OrderId: &v.OrderID,
						No:      &v.No,
						Amount:  pointy.GetPointer(moneyx.FormatAmount(int64(v.Amount))),
						Type:    pointy.GetPointer(uint32(v.Type)),
						Name:    &v.Name,
						Code:    &v.Code,
						Status:  pointy.GetPointer(uint32(v.Status)),
						PaidAt:  pointy.GetPointer(modelx.FormatNullDotTime(v.PaidAt, "")),
					})
				}
			}
		}

		idShipmentMap := make(map[uint64][]*order.OrderShipmentInfo)
		if in.WithShipments != nil && *in.WithShipments > 0 {
			subFilterMap := make(map[string]map[string][]any)
			subFilterMap[model.OrderShipmentColumns.OrderID] = map[string][]any{
				"in": oids,
			}
			list, _, err := l.svcCtx.Order.GetShipmentList(l.ctx, model.M{}, -1, subFilterMap)
			if err != nil {
				return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			}

			if len(list) > 0 {
				for _, v := range list {
					idShipmentMap[v.OrderID] = append(idShipmentMap[v.OrderID], &order.OrderShipmentInfo{
						Id:        &v.OrderShipmentID,
						OrderId:   &v.OrderID,
						No:        &v.No,
						Type:      pointy.GetPointer(uint32(v.Type)),
						Name:      &v.Name,
						Code:      &v.Code,
						Status:    pointy.GetPointer(uint32(v.Status)),
						UpdatedAt: pointy.GetPointer(modelx.FormatTime(v.UpdatedAt, "")),
					})
				}
			}
		}

		idLogMap := make(map[uint64][]*order.OrderOperateLogInfo)
		if in.WithLogs != nil && *in.WithLogs > 0 {
			subFilterMap := make(map[string]map[string][]any)
			subFilterMap[model.OrderOperateLogColumns.OrderID] = map[string][]any{
				"in": oids,
			}
			list, _, err := l.svcCtx.Order.GetLogList(l.ctx, model.M{}, -1, subFilterMap)
			if err != nil {
				return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			}

			if len(list) > 0 {
				for _, v := range list {
					idLogMap[v.OrderID] = append(idLogMap[v.OrderID], &order.OrderOperateLogInfo{
						Id:         &v.LogID,
						OrderId:    &v.OrderID,
						TradeState: pointy.GetPointer(uint32(v.TradeState)),
						NewState:   pointy.GetPointer(uint32(v.NewState)),
						Type:       pointy.GetPointer(uint32(v.Type)),
						Name:       &v.Name,
						Code:       &v.Code,
						Status:     pointy.GetPointer(uint32(v.Status)),
						Memo:       &v.Memo,
						OperatedBy: &v.OperatedBy,
						OperatedAt: pointy.GetPointer(modelx.FormatNullDotTime(v.OperatedAt, "")),
					})
				}
			}
		}

		for _, trade := range res {
			var skus []*order.OrderSkuInfo
			if ss, ok := idSkuMap[trade.ID]; ok {
				skus = ss[:]
			}
			var addresses []*order.OrderAddressInfo
			if as, ok := idAddressMap[trade.ID]; ok {
				addresses = as[:]
			}
			var adjustments []*order.OrderAdjustmentInfo
			if as, ok := idAdjustmentMap[trade.ID]; ok {
				adjustments = as[:]
			}
			var discounts []*order.OrderDiscountInfo
			if ds, ok := idDiscountMap[trade.ID]; ok {
				discounts = ds[:]
			}
			var payments []*order.OrderPaymentInfo
			if ps, ok := idPaymentMap[trade.ID]; ok {
				payments = ps[:]
			}
			var shipments []*order.OrderShipmentInfo
			if ss, ok := idShipmentMap[trade.ID]; ok {
				shipments = ss[:]
			}
			var logs []*order.OrderOperateLogInfo
			if ls, ok := idLogMap[trade.ID]; ok {
				logs = ls[:]
			}
			var synced *uint32
			if trade.Synced {
				synced = pointy.GetPointer(uint32(1))
			} else {
				synced = pointy.GetPointer(uint32(0))
			}

			resp.List = append(resp.List, &order.OrderInfo{
				Id:              &trade.ID,
				ParentId:        &trade.ParentID,
				UserId:          &trade.UserID,
				UserRank:        &trade.UserRank,
				Buyer:           &trade.Buyer,
				Sn:              &trade.OrderSN,
				OrderType:       pointy.GetPointer(uint32(trade.OrderType)),
				SourceType:      pointy.GetPointer(uint32(trade.SourceType)),
				Number:          pointy.GetPointer(uint32(trade.Quantity)),
				GemAmount:       pointy.GetPointer(moneyx.FormatGem(int64(trade.GemAmount))),
				RetailAmount:    pointy.GetPointer(moneyx.FormatAmount(int64(trade.RetailAmount))),
				Freight:         pointy.GetPointer(moneyx.FormatAmount(int64(trade.Freight))),
				DiscountAmount:  pointy.GetPointer(moneyx.FormatAmount(int64(trade.DiscountAmount))),
				AdjustAmount:    pointy.GetPointer(moneyx.FormatAmount(int64(trade.AdjustAmount))),
				ActualAmount:    pointy.GetPointer(moneyx.FormatAmount(int64(trade.ActualAmount))),
				DepositAmount:   pointy.GetPointer(moneyx.FormatAmount(int64(trade.DepositAmount))),
				BalanceAmount:   pointy.GetPointer(moneyx.FormatAmount(int64(trade.BalanceAmount))),
				RemainingAmount: pointy.GetPointer(moneyx.FormatAmount(int64(trade.RemainingAmount))),
				RefundAmount:    pointy.GetPointer(moneyx.FormatAmount(int64(trade.RefundAmount))),
				Gems:            &trade.Gems,
				TradeState:      pointy.GetPointer(uint32(trade.TradeState)),
				Remark:          &trade.Remark,
				SellerMemo:      &trade.SellerMemo,
				CreatedAt:       pointy.GetPointer(modelx.FormatTime(trade.CreatedAt, "")),
				UpdatedAt:       pointy.GetPointer(modelx.FormatTime(trade.UpdatedAt, "")),
				DeletedAt:       pointy.GetPointer(modelx.FormatNullDotTime(trade.DeletedAt, "")),
				PaidAt:          pointy.GetPointer(modelx.FormatNullDotTime(trade.PaidAt, "")),
				ShippedAt:       pointy.GetPointer(modelx.FormatNullDotTime(trade.ShippedAt, "")),
				DeliveredAt:     pointy.GetPointer(modelx.FormatNullDotTime(trade.DeliveredAt, "")),
				ConfirmedAt:     pointy.GetPointer(modelx.FormatNullDotTime(trade.ConfirmedAt, "")),
				ReviewedAt:      pointy.GetPointer(modelx.FormatNullDotTime(trade.ReviewedAt, "")),
				FulfilledAt:     pointy.GetPointer(modelx.FormatNullDotTime(trade.FulfilledAt, "")),
				ClosedAt:        pointy.GetPointer(modelx.FormatNullDotTime(trade.ClosedAt, "")),
				AutoComfirmDays: pointy.GetPointer(uint32(trade.AutoComfirmDays)),
				Growth:          pointy.GetPointer(uint32(trade.Growth)),
				Integrals:       pointy.GetPointer(uint32(trade.Integrals)),
				Synced:          synced,
				Skus:            skus,
				Addresses:       addresses,
				Adjustments:     adjustments,
				Discounts:       discounts,
				Payments:        payments,
				Shipments:       shipments,
				Logs:            logs,
			})
		}
	}

	return resp, nil
}
